package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.service.DynamicService;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductTypeService;
import com.wing.product.service.ProductUnitService;
import com.wing.purchase.dao.PurchasePlanDao;
import com.wing.purchase.model.entity.PurReturnGoodsRecordsDetail;
import com.wing.purchase.model.entity.PurchasePlan;
import com.wing.purchase.model.entity.PurchasePlanDetail;
import com.wing.purchase.model.entity.PurchaseType;
import com.wing.purchase.model.request.PurchasePlanForm;
import com.wing.purchase.model.response.PurchasePlanVO;
import com.wing.storage.model.entity.ProductInventory;
import com.wing.storage.service.ProductInventoryService;
import com.wing.user.feign.UserClient;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 领料计划-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurchasePlanServiceImpl extends ServiceImpl<PurchasePlanDao, PurchasePlan> implements PurchasePlanService {

    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private PurchasePlanDetailService purchasePlanDetailService;
    @Autowired
    private  ProductDetailService productDetailService;
    @Autowired
    private  ProductTypeService productTypeService;
    @Autowired
    private  ProductUnitService productUnitService;

    @Autowired
    private PurchaseTypeService purchaseTypeService;

    @Autowired
    private ProductInventoryService productInventoryService;

    @Autowired
    private UserClient userClient;

    @Override
    @Transactional(readOnly = false)
    public int add(PurchasePlanForm purchasePlanForm) {

        //校验
        PurchasePlan purchasePlan = new PurchasePlan();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(PurchasePlan.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchasePlanForm, purchasePlan, copyOptions);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("plan_no", "pur_purchase_plan");
        String day = simpleDateFormat.format(new Date());
        purchasePlan.setPlanNo("PP" + day + code);
        purchasePlan.setCreateTime(LocalDateTime.now());
        purchasePlan.setDepartmentId(JwtUtils.getDepartmentId());
        purchasePlan.setUpdateTime(LocalDateTime.now());
        purchasePlan.setCreatorName(JwtUtils.getLoginUsername());
        purchasePlan.setCreator(JwtUtils.getLoginUserId());
        purchasePlan.setSkuQuantity(purchasePlanForm.getPlanInfoList().size());
        //累计总金额
        if (!CollectionUtils.isEmpty(purchasePlanForm.getPlanInfoList())) {
            BigDecimal total = purchasePlanForm.getPlanInfoList().stream()
                    // 过滤价格为0.00的产品
                    .filter(product -> product.getCurrentCostPrice().compareTo(BigDecimal.ZERO)!= 0)
                    .map(product -> product.getCurrentCostPrice().multiply(product.getPurchaseNumber()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            purchasePlan.setTotalMoney(total);
        }
        int i = baseMapper.insert(purchasePlan);
        if (i > 0) {
            for (PurchasePlanDetail purchasePlanDetail : purchasePlanForm.getPlanInfoList()) {
                purchasePlanDetail.setCreateTime(LocalDateTime.now());
                purchasePlanDetail.setUpdateTime(LocalDateTime.now());
                purchasePlanDetail.setCreatorName(JwtUtils.getLoginUsername());
                purchasePlanDetail.setCreator(JwtUtils.getLoginUserId());
                purchasePlanDetail.setPlanId(purchasePlan.getId());
                purchasePlanDetail.setLastChangeTime(LocalDateTime.now().toString());
            }
            purchasePlanDetailService.saveBatch(purchasePlanForm.getPlanInfoList());
        }
        return i;
    }

    @Override
    @Transactional(readOnly = false)
    public int update(PurchasePlan purchasePlan) {
        if (purchasePlan.getStatus().equals(PurchasePlan.Status.fail)) {
            // 审核拒绝状态修改之后将状态修改为待确认
            purchasePlan.setStatus(PurchasePlan.Status.stayConfirm);
        }
        return updateDate(purchasePlan);
    }

    @Override
    public List<PurchasePlanVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<PurchasePlanVO> pageList4app(Page page, Map<String, Object> params) {
        List<PurchasePlanVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public PurchasePlanVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional(readOnly = false)
    public boolean delete(Long purchasePlanId) {
        int i = baseMapper.deleteById(purchasePlanId);
        if (i > 0) {
            // 删除明细
            purchasePlanDetailService.remove(new QueryWrapper<PurchasePlanDetail>().eq("plan_id", purchasePlanId));
        }
        return i > 0;
    }

    @Override
    public List<PurchasePlanDetail> getDetailInfo(Integer planId) {
        return purchasePlanDetailService.list(new QueryWrapper<PurchasePlanDetail>().eq("plan_id", planId));
    }

    @Override
    public int confirm(Integer id) {
        PurchasePlan purchasePlan = baseMapper.selectById(id);
        purchasePlan.setStatus(PurchasePlan.Status.stayAudit);
        purchasePlan.setAffirmant(JwtUtils.getLoginUserId());
        return baseMapper.updateById(purchasePlan);
    }

    @Override
    @Transactional(readOnly = false)
    public int audit(PurchasePlan purchasePlan) {
        purchasePlan.setAuditTime(LocalDateTime.now());
        purchasePlan.setAuditor(JwtUtils.getLoginUserId());
        return updateDate(purchasePlan);
    }

    /**
     * 修改领料计划
     *
     * @param purchasePlanForm
     * @return
     */
    @Override
    public int updateInfoBy(PurchasePlanForm purchasePlanForm) {
        PurchasePlan byId = this.getById(purchasePlanForm.getId());
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(PurchasePlan.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchasePlanForm, byId, copyOptions);
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        byId.setSkuQuantity(purchasePlanForm.getPlanInfoList().size());
        //累计总金额
        if (!CollectionUtils.isEmpty(purchasePlanForm.getPlanInfoList())) {
            BigDecimal total = purchasePlanForm.getPlanInfoList().stream()
                    // 过滤价格为0.00的产品
                    .filter(product -> product.getCurrentCostPrice().compareTo(BigDecimal.ZERO)!= 0)
                    .map(product -> product.getCurrentCostPrice().multiply(product.getPurchaseNumber()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            byId.setTotalMoney(total);
        }

        if (this.update(byId) > 0) {
            List<PurchasePlanDetail> planInfoList = purchasePlanForm.getPlanInfoList();
            boolean b = this.purchasePlanDetailService.updateBatchById(planInfoList);
            if (b) {
                return 1;
            }
        }
        return 0;
    }

    /**
     * 获取部门详情信息
     * @param id
     * @return
     */
    @Override
    public PurchasePlanVO getDetailBy(Integer id) {
        Map<String, Object> params = new HashMap<>();
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if(StringUtils.isNotBlank(DynamicDataSource.name.get())){
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        params.put("databaseUser", databaseUser);
        PurchasePlanVO detailBy = baseMapper.getDetailBy(id,params);
        //获取采购类型名称
        PurchaseType purchaseType = purchaseTypeService.getById(detailBy.getPurTypeId());
        if (ObjectUtil.isNotNull(purchaseType)) {
            detailBy.setPurTypeName(purchaseType.getPurchaseTypeName());
            detailBy.setPostId(purchaseType.getStationsId());
            detailBy.setPostName(purchaseType.getStations());
        }
        List<ProductDetail> details = productDetailService.list();
        Map<String, String> stringMap = productTypeService.list().stream().collect(Collectors.toMap(info->info.getId().toString(), info->info.getName()));
        Map<Long, String> map = productUnitService.list().stream().collect(Collectors.toMap(ProductUnitInfo::getId, ProductUnitInfo::getName));
        //查询出详情
        QueryWrapper<PurchasePlanDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("plan_id", id);
        wrapper.eq("is_deleted", false);
        List<PurchasePlanDetail> list = this.purchasePlanDetailService.list(wrapper);
        //库存
        List<ProductInventory> productInventories = productInventoryService.list();
        list.forEach(purchasePlanDetail -> {
            //类别
            purchasePlanDetail.setProductCategoryName(stringMap.get(purchasePlanDetail.getProductCategory()));
            //sku参数
            details.forEach(productDetail -> {
                if (productDetail.getSkuCode().equals(purchasePlanDetail.getSkuCode())){
                    purchasePlanDetail.setSkuCode(productDetail.getSkuCode());
                    purchasePlanDetail.setProductName(productDetail.getSkuName());
                    purchasePlanDetail.setSpecifications(productDetail.getSkuSpec());
                    purchasePlanDetail.setCurrentCostPrice(productDetail.getCurrentCostPrice());
                    purchasePlanDetail.setMainUnitId(productDetail.getMainUnitId());
                    purchasePlanDetail.setMainUnitName(map.get(productDetail.getMainUnitId()));
                }
            });
            //库存
            productInventories.forEach(productInventory -> {
               if (productInventory.getProductDetailId().equals(purchasePlanDetail.getProductDetailId())){
                   purchasePlanDetail.setHaveQuantity(productInventory.getQuantity());
               }
            });
        });
        detailBy.setPlanInfoList(list);
        return detailBy;
    }


    public int updateDate(PurchasePlan purchasePlan) {
        int i = baseMapper.updateById(purchasePlan);
        if (i > 0) {
            List<PurchasePlanDetail> addDetails = new ArrayList<>();
            List<PurchasePlanDetail> updDetails = new ArrayList<>();
            List<Long> delDetails = new ArrayList<>();
            List<Long> ids = new ArrayList<>();
            for (PurchasePlanDetail purchasePlanDetail : purchasePlan.getPlanInfoList()) {
                if (null == purchasePlanDetail.getId()) {
                    purchasePlanDetail.setCreator(JwtUtils.getLoginUserId());
                    purchasePlanDetail.setCreatorName(JwtUtils.getLoginUsername());
                    purchasePlanDetail.setModifier(JwtUtils.getLoginUserId());
                    purchasePlanDetail.setModifierName(JwtUtils.getLoginUsername());
                    purchasePlanDetail.setPlanId(purchasePlan.getId());
                    addDetails.add(purchasePlanDetail);
                } else {
                    ids.add(purchasePlanDetail.getId());
                    updDetails.add(purchasePlanDetail);
                }
            }
            // 查询旧数据
            List<PurchasePlanDetail> oldDetails = purchasePlanDetailService.list(new QueryWrapper<PurchasePlanDetail>().eq("plan_id", purchasePlan.getId()));
            for (PurchasePlanDetail oldDetail : oldDetails) {
                if (!ids.contains(oldDetail.getId())) {
                    delDetails.add(oldDetail.getId());
                }
            }
            if (addDetails.size() > 0) {
                purchasePlanDetailService.saveBatch(addDetails);
            }
            if (updDetails.size() > 0) {
                purchasePlanDetailService.updateBatchById(updDetails);
            }
            if (delDetails.size() > 0) {
                purchasePlanDetailService.removeByIds(delDetails);
            }
        }
        return i;
    }

}
